import { FULL_PATH, PREFIX } from "./config";
import ExifReader from "exifreader";
import prettyBytes from "pretty-bytes";
// @ts-ignore
import extractChunks from "png-chunks-extract";

const fs = require("fs");
const path = require("path");
const qs = require("qs");

type PictureInfo = {
  fileName: string;
  tags?: string;
  prefix: string;
  ctime?: number;
  negative_tags?: string;
};

async function readExif(fileFullUrl: string) {
  const file = fileFullUrl;
  const data = await ExifReader.load(file);
  const entries = Object.entries(data);
  // exifRef.value = entries.map(([key, value]) => ({ key, value }));
  // debugger
  // console.log(entries);
}

/*
async function readNovelaiTag(file) {
  const buf = await file.arrayBuffer();
  const chunks = extractChunks(new Uint8Array(buf));
  const textChunks = chunks
      .filter(function (chunk) {
        return chunk.name === "tEXt" || chunk.name === "iTXt";
      })
      .map(function (chunk) {
        if (chunk.name === "iTXt") {
          let data = chunk.data.filter((x) => x != 0x0);
          let txt = new TextDecoder().decode(data);
          return {
            keyword: "信息",
            text: txt.slice(11),
          };
        }
        return text.decode(chunk.data);
      });
  console.log(textChunks);
  return textChunks;
}*/

const updateFileInfoMysql = async (
  fileName: string,
  fileNameInFtp: string,
  tags?: string
) => {
  const stat = fs.statSync(fileName);
  let data: PictureInfo = {
    prefix: PREFIX,
    tags: tags as string,
    negative_tags: "",
    fileName: fileNameInFtp,
    ctime: parseInt(stat.ctimeMs),
  };
  console.log(data);
  return fetch(FULL_PATH, {
    method: "POST",
    body: qs.stringify(data), // data can be `string` or {object}!
    headers: new Headers({
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "application/json, text/plain, */*",
    }),
    mode: "cors",
  });
};

export { updateFileInfoMysql };
